package com.milk.servlet;

import com.milk.Dao.ReportDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;


public class ReportManagementServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应的字符编码为 UTF-8
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        String action = request.getPathInfo();
        if (action == null || action.equals("/")) {
            action = "/list"; // 默认操作是列出所有报表
        }

        switch (action) {
            case "/countSalesByDay":
                countSalesByDay(request, response);
                break;
            case "/sumSalesByCategory":
                sumSalesByCategory(request, response);
                break;
            default:
                // 处理其他不支持的GET请求
                response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        }
    }

    private void countSalesByDay(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应内容类型为HTML，并指定字符编码为 UTF-8
        response.setContentType("text/html;charset=UTF-8");

        // 获取开始日期和结束日期参数
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");

        // 调用ReportDao的方法按时间段统计销售数量
        Map<String, Integer> salesCountMap = ReportDao.countSalesByDay(startDate, endDate);
        request.setAttribute("salesCountMap", salesCountMap);

        // 转发到报表统计页面（假设为report_management.jsp）
        request.getRequestDispatcher("/report_management.jsp").forward(request, response);
    }

    private void sumSalesByCategory(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应内容类型为HTML，并指定字符编码为 UTF-8
        response.setContentType("text/html;charset=UTF-8");

        // 调用ReportDao的方法按饮品分类统计销售金额
        Map<String, Double> salesAmountMap = ReportDao.sumSalesByCategory();

        // 打印查询结果
        System.out.println("按饮品分类统计销售金额: " + salesAmountMap);

        request.setAttribute("salesAmountMap", salesAmountMap);

        // 转发到报表统计页面（假设为report_management.jsp）
        request.getRequestDispatcher("/report_management.jsp").forward(request, response);
    }
}